﻿using System;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.cbuilder.MSILSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder {
    internal class StoreObjectTranslator : ITranslator {
        public ICStatement TranslateAndAdd(CMethodBody methodBody, CBasicBlock currentBlock, BasicBlock block, Instruction instruction) {
            if(instruction.InlineType == null)
            {
                throw new Exception("expected instruction: " + instruction + " to have an inline type");
            }
            IVariable sourceValue = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            if(sourceValue.IsPointer) {
                throw new Exception("expected source to not be a pointer: " + sourceValue.ToString());
            }
            IVariable targetPtr = EvaluationStackHelper.PopVariableOffEvaluationStack(currentBlock);
            if (!targetPtr.IsPointer) {
                throw new Exception("expected target to be a pointer: " + targetPtr.ToString());
            }
            AssignToLocalVariable assignStm = new AssignToLocalVariable(sourceValue, targetPtr){DereferenceTargetPointer = true, OnStack = false};
            currentBlock.Statements.Add(assignStm);
            return assignStm;
        }
    }
}
